package com.wxh.bomb.netty.design.masterwoker.core;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 任务处理者
 *
 * @author wxh
 * @date：2017.10.10
 */
public abstract class Worker implements Runnable {

    // master的任务队列
    private ConcurrentLinkedQueue<Task> taskQueue;
    // master的结果集
    private ConcurrentHashMap<String, Object> results;

    /**
     * 任务处理者实例化
     *
     * @param taskQueue
     * @param results
     */
    public void init(ConcurrentLinkedQueue<Task> taskQueue, ConcurrentHashMap<String, Object> results) {
        this.taskQueue = taskQueue;
        this.results = results;
    }

    @Override
    public void run() {
        while (true) {
            Task task = this.taskQueue.poll();
            if (task == null) {
                break;
            }

            Object object = handle(task);
            // 装在处理结果
            this.results.put(task.getId() + "", object);

        }

    }

    /**
     * 处理任务
     *s
     * @param input
     * @return
     */
    public abstract Object handle(Task input);
}
